// import Vue from 'vue'
import axios from 'axios'
import { VueAxios } from './axios'
import { Dialog } from 'vant'
import store from '../store'
// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 30000, // 请求超时时间
  // headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})

const err = (error) => {
  store.dispatch('showLoading', {isLoading: false})
  console.log(error)
  if (error.message.includes('timeout')) {
    Dialog.alert({
      title: '提示',
      message: '连接超时',
    })
  }
  if (error.message.includes('Network')) {
    Dialog.alert({
      title: '提示',
      message: '网络异常',
    })
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  store.dispatch('showLoading', {isLoading: true})
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  store.dispatch('showLoading', {isLoading: false})
  if (response.data.status) {
    return response.data
  } else {
    if (response.data.msg) {
      throw new Error(response.data.msg)
    } else {
      throw new Error('请求异常')
    }
  }
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
